package com.xxx.ware.ware_manage_sys.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class CommonUtil {
    //生成随机字符串
    public static String generateUUID(){
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    //MD5加密
    public static String md5(String key){
        if (StringUtils.isBlank(key)){//isBlank：null， ""，空格都判定为空，返回true
            return null;
        }
        return DigestUtils.md5DigestAsHex(key.getBytes());//md5DigestAsHex：将传入的结果转成16进制数的字符串后返回
    }

    /**
     * 获取json字符串
     * @param code 响应码
     * @param msg 响应信息
     * @param map 传送的数据
     * @return 返回响应信息的json字符串
     */
    public static String getJSONString(int code, String msg, Map<String, Object> map){

        JSONObject json = new JSONObject();

        json.put("code", code);
        json.put("msg", msg);

        if (map != null){
            for (String key : map.keySet()){
                json.put(key, map.get(key));
            }
        }

        return json.toJSONString();
    }

    public static String getJSONString(int code, String msg){
        return getJSONString(code, msg, null);
    }

    public static String getJSONString(int code){
        return getJSONString(code, null, null);
    }

    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        map.put("A", 123);
        map.put("D", "abc");

        String b = getJSONString(5, "B", map);
        System.out.println(b);
    }
}
